//
//  WPNewThirdTVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/11/24.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPNewThirdTVC.h"
#import "WPNewCommentCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WPNewCommentModel.h"
#import "WPDetailCommentVC.h"
#import "WPMRModel.h"


@interface WPNewThirdTVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,copy)NSString *url;
@property(nonatomic,strong)UIView *noCommentView;
@property(nonatomic,strong)NSMutableArray *models;

@property(nonatomic,assign)int indexPage;

@end

@implementation WPNewThirdTVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:[NSString stringWithUTF8String:object_getClassName(self)]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = GlobalBgColor;
    [self.tableView registerClass:[WPNewCommentCell class] forCellReuseIdentifier:@"WPNewCommentCell"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //      刷新数据
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.tableView.mj_header endRefreshing];
        });
    }];
    self.tableView.mj_header = mj_header;
    [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    mj_header.stateLabel.textColor = GLobalFontColor;
    mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
    
    //    上拉刷新控件
    MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakSelf loadMoreData];
        [weakSelf.tableView.mj_footer endRefreshing];
        
    }];
    self.tableView.mj_footer = mj_footer;
    mj_footer.automaticallyRefresh = NO;
    mj_footer.automaticallyHidden = NO;
    
}

-(void)setModel:(WPMRModel *)model
{
    _model = model;
    
    self.url = @"appraise/findAppraise.do";
    NSDictionary *dict = @{@"recordId":@(self.model.id)};
    
    [self showWithStatus:@"正在加载"];
    
    [[WPNetWorkManager sharedNetWorkManager] POST:self.url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"评论:%@",responseObject);
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            NSArray *arr = responseDict[@"detail"];
            //有评论的时候
            if (arr.count)
            {
                //不满一页影藏底部刷新控件
                if (arr.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                
                for (NSDictionary *dict in arr)
                {
                    WPNewCommentModel *model = [WPNewCommentModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                //评论页数置为1
                self.indexPage = 1;
                
                [self.tableView reloadData];
            }
            else
            {
                //展示没有评论的界面
                [self showNoCommentView];
            }
            
            [self dismiss];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

//加载更多数据
-(void)loadMoreData
{
    
    NSDictionary *dict = @{@"recordId":@(self.model.id),@"page":@(self.indexPage)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:self.url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        
        NSDictionary *responseDict = (NSDictionary *)responseObject;
        if ([responseDict[@"result"] isEqualToString:@"success"])
        {
            NSArray *arr = responseDict[@"detail"];
            
            //            有评论的时候
            if (arr.count)
            {
                //            不满一页影藏底部刷新控件
                if (arr.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                
                for (NSDictionary *dict in arr)
                {
                    WPNewCommentModel *model = [WPNewCommentModel yy_modelWithDictionary:dict];
                    [self.models addObject:model];
                }
                
                //评论页数加1
                self.indexPage++;
                
                [self.tableView.mj_footer endRefreshing];
                [self.tableView reloadData];
            }
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error)
        {
            [self showErrorInfoWithStatus:@"网络错误"];
        }
        
    }];
}

-(void)showNoCommentView
{
    UIView *noCommentView = [UIView new];
    noCommentView.backgroundColor = [UIColor whiteColor];
    noCommentView.frame = self.view.bounds;
    [self.view addSubview:noCommentView];
    
    UIImageView *noCommentImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no_comment"]];
    [noCommentImageView sizeToFit];
    [noCommentView addSubview:noCommentImageView];
    
    [noCommentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(noCommentView);
        make.top.equalTo(noCommentView).offset(85*kMoreDetailCaseScale);
    }];
    
    UILabel *noCommentLabel = [UILabel new];
    noCommentLabel.text = @"暂无其他评论";
    noCommentLabel.font = [UIFont systemFontOfSize:14];
    noCommentLabel.textColor = GloballightFontColor;
    [noCommentView addSubview:noCommentLabel];
    
    [noCommentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(noCommentView);
        make.top.equalTo(noCommentImageView.mas_bottom).offset(20*kMoreDetailCaseScale);
    }];
}



#pragma mark - tableView的数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPNewCommentCell"];
    cell.model = self.models[indexPath.item];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"WPNewCommentCell" cacheByIndexPath:indexPath configuration:^(WPNewCommentCell *cell) {
        // 配置 cell 的数据源，和 "cellForRow" 干的事一致，比如：
        cell.model = self.models[indexPath.item];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewCommentModel *model = self.models[indexPath.item];
    
    if (model.replyAmount)
    {
        WPDetailCommentVC *vc = [WPDetailCommentVC new];
        vc.recordId = self.model.id;
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

-(NSMutableArray *)models
{
    if(_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

@end
